<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        height: 10000px;
        width: 100%;
        overflow: scroll;
      }
    </style>
  </head>

  <body>
    <input type="text" id="ipt" />
  </body>
  <script>
    /*
            防抖debounce
1.监听一个输入框的文字变化后触发change事件
2.直接用keyup事件，则会频发触发change事件
3.防抖:用户输入结束或暂停时，才会触发change事件
    */

    ipt.onkeyup = debounce((e) => {
      console.log(e, "e");
    });
    function debounce(fn, delay = 200) {
      let timer = null;
      return function () {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, arguments);
          timer = null;
        }, delay);
      };
    }
    //       节流
    //1.拖拽一个元素时，要随时拿到该元素被拖拽的位置
    //2.直接用drag事件，则会频发触发mousemove事件，很容易导致卡顿
    //3.节流:无论拖拽速度多块，都会每隔100ms触发一次
    function throttle(fn, delay = 200) {
      let timer = null;
      return function () {
        if (timer) return;

        timer = setTimeout(() => {
          fn.apply(this, arguments);
          timer = null;
        }, delay);
      };
    }
    document.body.onscroll = throttle((e, b, c) => {
      console.log(e, "e");
    }, 200);
  </script>
</html>
